<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style=" margin-bottom:20px ;">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 表单 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <div style="margin-top: 15px;">
          <el-input placeholder="请输入要查询的用户名" v-model="userObj.query" clearable class="input-with-select">
            <el-button slot="append" @click="getUserList()" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </el-col>
      <!-- 表单按钮 -->
      <el-col :span="8">
        <div style="margin-top: 15px; text-align: left;">
          <el-button @click="addUser()" type="primary">添加用户</el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      max-height="400px"
      size="small"
      :highlight-current-row="true"
      :border="true"
      :resizable="true"
      style="width: 100%;margin:20px 0;"
    >
      <el-table-column type="index" width="50" label="#"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="140"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="140"></el-table-column>
      <el-table-column prop="role_name" label="角色" width="100"></el-table-column>
      <el-table-column prop="address" label="状态">
        <!-- 按钮 -->
        <template slot-scope="scope">
          <el-switch
            @change="changeUser(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" width="250">
        <!-- 按钮 -->
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="centerDialogVisible = true,handleEdit(scope.row.id)"
          >
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">
            <i class="el-icon-delete"></i>
          </el-button>
          <el-tooltip content="分配角色" placement="top">
          <el-button @click="dialogFormVisibleAuth=true,handleAuth(scope.row)" size="mini" type="warning">
            <i class="el-icon-s-tools"></i>
          </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userObj.pagenum"
        :page-sizes="[1, 10,15, 20]"
        :page-size="userObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 编辑弹出层 -->
    <el-dialog title="提示" :visible.sync="centerDialogVisible" width="50%" center>
      <span>
        <!-- 弹出表单  -->
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <!-- 用户名 -->
          <el-form-item label="用户名">
            <el-input v-model="username" disabled></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <!-- 电话号码 -->
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddBtn('form')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加用户弹出层 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="formAdd"  ref="formAdd" :rules="addRules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="formAdd.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="formAdd.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="formAdd.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="formAdd.mobile" autocomplete="off"></el-input>
        </el-form-item>
  
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBtnUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色弹出层 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleAuth">
  <el-form :model="formAuth">
    <el-form-item label="当前用户：" :label-width="formLabelWidth">
      {{formAuth.username}}
    </el-form-item>
    <el-form-item label="当前角色：" :label-width="formLabelWidth">
       {{formAuth.role_name}}
    </el-form-item>
    <el-form-item label="分配的新角色:" :label-width="formLabelWidth">
      <el-select v-model="formAuth.rid" placeholder="请选择角色">
        <el-option v-for="(item,index) in GetroleList" :key="index" :label="item.roleName" :value="item.id"></el-option>
        
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click=" dialogFormVisibleAuth=false">取 消</el-button>
    <el-button type="primary" @click="HeadlerAuth">确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>
<script>
// 导入 获取用户列表的请求
import { users_api, deitUser_api,addusers_api,UsersRolesAuth_api,rolesList_api } from "@/api/index.js";
import { getuser_api } from "@/api/index.js";
// 导入 删除用户的请求
import { delete_api } from "@/api/index.js";
// 编辑用户信息
import { put_api } from "@/api/index.js";
export default {
  data() {
    return {
      form: {
        id: "",
        email: "",
        mobile: "",
      },
      formAdd:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      // 分配角色
      formAuth:{

      },
      GetroleList:{},
      UserSetID:{
        id:JSON.parse(window.sessionStorage.getItem('user')).id,
        rid:''
      },
      total: 1,
      username: "",
      tableData: [],
      input3: "",
      value: true,
      //   分页数据

      //   编辑弹出层
      centerDialogVisible: false,
      dialogFormVisibleAuth:false,
      // 添加用户 
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      //定义一个传入获取用户列表的实参
      userObj: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      rules: {
        //用户名表单验证
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        // 密码表单验证
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      addRules: {
        //用户名表单验证
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        // 密码表单验证
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
    };
  },
  created() {
    //调用获取用户列表的方法
    this.getUserList();
    this.getRolesList()
  },
  methods: {
    // 添加用户
   async addBtnUser(){
    //  二次验证
     this.$refs.formAdd.validate(async (valid)=>{
       if(!valid) return
        this.dialogFormVisible=false
        var {data:res} = await addusers_api(this.formAdd)
            this.$message({
            message: res.meta.msg,
            type: "success",
          });
           //调用获取用户列表的方法
       this.getUserList(); 
              // 清空表单数据
      this.$refs.formAdd.resetFields()
     })
      
    },
 
    //   编辑
    async handleEdit(rowId) {
      const res = await getuser_api(rowId);
      //  console.log(res);

      //   赋值
      this.form.id = rowId;
      this.form.email = res.data.data.email;
      this.form.mobile = res.data.data.mobile;
      this.username = res.data.data.username;
    },
    // 编辑成功
    async AddBtn(form) {
      // 二次验证
      this.$refs[form].validate(async (valid) => {
        if (!valid) return;
        this.centerDialogVisible = false;
        if (valid) {
          const res = await put_api(this.form);
          // console.log(res);
          if (res.data.meta.status != 200) return;
          this.$message({
            message: res.data.meta.msg,
            type: "success",
          });

          // 刷新列表
          this.getUserList();
        } else {
          return;
        }
      });
    },
    // 添加用户
    addUser() {
      this.dialogFormVisible=true
    },
    // 删除用户
    handleDelete(rowId) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //   发送请求
          const res = await delete_api(rowId);
          this.$message({
            type: "success",
            message: res.data.meta.msg,
          });
          // 刷新列表
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改用户状态
    async changeUser(row) {
      const { data: res } = await deitUser_api({
        uId: row.id,
        type: row.mg_state,
      });
      console.log(res);
      if (res.meta.status != 200) return;
      this.$message({
        message: res.meta.msg,
        type: "success",
      });
    },
    // 分页逻辑
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.userObj.pagesize = val;
      // 刷新列表
      this.getUserList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.userObj.pagenum = val;
      // 刷新列表
      this.getUserList();
    },
    // 定义一个获取用户列表数据的函数
    async getUserList() {
      const res = await users_api(this.userObj);
      // console.log(res);
      this.total = res.data.data.total;
      // 赋值到数据层
      this.tableData = res.data.data.users;
    },
// 获取角色列表
    async getRolesList() {
      const { data: res } = await rolesList_api();
        // console.log(res, 1111);
      this.GetroleList = res.data;
    },
    // 分配角色
   handleAuth(row){
     this.formAuth = row
    //  console.log(row,888);
      this.UserSetID.rid = row.id
    },
   async HeadlerAuth(){
    this.dialogFormVisibleAuth=false
    const {data:res} = await UsersRolesAuth_api(this.UserSetID)
      // console.log(res,9999);
        this.$message({
        message: res.meta.msg,
        type: "success",
      });
    }
  },
};
</script>
<style lang="less" scoped>
</style>